// EU Commission UI 集成功能
class EUCommissionUI {
    constructor() {
        this.isRunning = false;
        this.results = [];
        this.logContainer = null;
        this.resultsContainer = null;
        this.progressBar = null;
        this.progressText = null;
        this.progressContainer = null;
        this.currentProcess = null;
        this.consoleLogListener = null;
    }

    // 初始化UI元素
    initializeElements() {
        console.log('EU Commission UI: 开始初始化元素...');
        
        this.logContainer = document.getElementById('eu-log');
        this.resultsContainer = document.getElementById('eu-results');
        this.progressBar = document.getElementById('eu-progress-bar');
        this.progressText = document.getElementById('eu-progress-text');
        this.progressContainer = document.getElementById('eu-progress-container');
        
        // 调试信息
        console.log('EU Commission UI: 元素查找结果:', {
            logContainer: !!this.logContainer,
            resultsContainer: !!this.resultsContainer,
            progressBar: !!this.progressBar,
            progressText: !!this.progressText,
            progressContainer: !!this.progressContainer
        });
        
        // 初始化控制台监控
        this.initializeConsoleMonitoring();
        
        // 绑定按钮事件
        this.bindEvents();
        
        // 初始化按钮状态
        this.updateButtonStates();
        
        console.log('EU Commission UI: 元素初始化完成');
    }

    // 绑定事件
    bindEvents() {
        console.log('EU Commission UI: 开始绑定事件...');
        
        const startBtn = document.getElementById('eu-start-btn');
        const stopBtn = document.getElementById('eu-stop-btn');
        const exportBtn = document.getElementById('eu-export-btn');
        
        console.log('EU Commission UI: 按钮元素查找结果:', {
            startBtn: !!startBtn,
            stopBtn: !!stopBtn,
            exportBtn: !!exportBtn
        });
        
        if (startBtn) {
            startBtn.addEventListener('click', () => {
                console.log('EU Commission UI: 开始按钮被点击');
                this.startScraping();
            });
            console.log('EU Commission UI: 开始按钮事件已绑定');
        } else {
            console.error('EU Commission UI: 找不到开始按钮元素 #eu-start-btn');
        }
        
        if (stopBtn) {
            stopBtn.addEventListener('click', () => {
                console.log('EU Commission UI: 停止按钮被点击');
                this.stopScraping();
            });
            console.log('EU Commission UI: 停止按钮事件已绑定');
        } else {
            console.error('EU Commission UI: 找不到停止按钮元素 #eu-stop-btn');
        }
        
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                console.log('EU Commission UI: 导出按钮被点击');
                this.exportData();
            });
            console.log('EU Commission UI: 导出按钮事件已绑定');
        } else {
            console.error('EU Commission UI: 找不到导出按钮元素 #eu-export-btn');
        }
        
        console.log('EU Commission UI: 事件绑定完成');
    }

    // 初始化控制台监控
    initializeConsoleMonitoring() {
        console.log('EU Commission UI: 初始化控制台监控...');
        
        // 检查是否存在控制台API
        if (typeof consoleAPI !== 'undefined') {
            console.log('EU Commission UI: 找到控制台API，开始监控');
            
            // 设置控制台日志监听器
            this.consoleLogListener = (log) => {
                this.displayConsoleLog(log);
            };
            
            // 开始监听控制台日志
            consoleAPI.onConsoleLog(this.consoleLogListener);
            
            // 开始控制台监控
            consoleAPI.startConsoleMonitoring();
            
            console.log('EU Commission UI: 控制台监控已启动');
        } else {
            console.warn('EU Commission UI: 控制台API不可用，使用本地日志');
        }
    }
    
    // 显示控制台日志
    displayConsoleLog(log) {
        if (!this.logContainer) return;
        
        // 过滤只显示相关的日志（包含EU Commission相关关键词）
        const message = log.message || '';
        const isRelevant = message.includes('EU Commission') || 
                          message.includes('eucommission') || 
                          message.includes('eu-commission') ||
                          message.includes('正在导入') ||
                          message.includes('浏览器') ||
                          message.includes('页面') ||
                          message.includes('抓取') ||
                          message.includes('标准') ||
                          message.includes('处理');
        
        if (isRelevant) {
            const timestamp = new Date(log.timestamp).toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${log.level || 'info'}`;
            logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
            
            this.logContainer.appendChild(logEntry);
            this.logContainer.scrollTop = this.logContainer.scrollHeight;
        }
    }
    
    // 记录日志
    log(message, type = 'info') {
        if (!this.logContainer) return;
        
        const timestamp = new Date().toLocaleTimeString();
        const logEntry = document.createElement('div');
        logEntry.className = `log-entry log-${type}`;
        logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
        
        this.logContainer.appendChild(logEntry);
        this.logContainer.scrollTop = this.logContainer.scrollHeight;
        
        // 同时发送到控制台监控系统
        if (typeof consoleAPI !== 'undefined') {
            consoleAPI.addConsoleLog(type, `EU Commission UI: ${message}`);
        }
    }

    // 更新进度条
    updateProgress(current, total, message = '') {
        if (!this.progressBar || !this.progressText) return;
        
        const percentage = Math.round((current / total) * 100);
        this.progressBar.style.width = `${percentage}%`;
        this.progressText.textContent = message || `${percentage}%`;
    }

    // 显示进度条
    showProgress() {
        if (this.progressContainer) {
            this.progressContainer.style.display = 'block';
        }
    }

    // 隐藏进度条
    hideProgress() {
        if (this.progressContainer) {
            this.progressContainer.style.display = 'none';
        }
    }

    // 开始抓取
    async startScraping() {
        console.log('EU Commission UI: startScraping 被调用');
        
        if (this.isRunning) {
            this.log('抓取任务已在运行中...', 'warning');
            return;
        }

        this.isRunning = true;
        this.results = [];
        this.clearResults();
        this.clearLogs(); // 清空日志
        this.log('开始EU Commission页面抓取任务', 'info');
        this.showProgress();
        this.updateProgress(0, 100, '初始化中...');
        this.updateButtonStates();

        try {
            // 检查浏览器模式设置
            const headlessSwitch = document.getElementById('eu-headless-switch');
            const isHeadless = !headlessSwitch.checked;
            
            this.log(`浏览器模式: ${isHeadless ? '隐藏' : '显示'}`, 'info');
            
            // 调用后端Node.js功能
            await this.callBackendScraper(isHeadless);

        } catch (error) {
            this.log(`抓取过程中发生错误: ${error.message}`, 'error');
        } finally {
            this.isRunning = false;
            this.hideProgress();
            this.updateButtonStates();
        }
    }

    // 调用后端抓取功能
    async callBackendScraper(headless = true) {
        try {
            // 检查是否在Electron环境中
            if (typeof pluginAPI !== 'undefined') {
                // 使用pluginAPI调用Node.js功能
                this.log('正在启动后端抓取服务...', 'info');
                this.updateProgress(10, 100, '启动服务中...');
                
                const scriptParams = {
                    pluginName: 'info-update',
                    script: 'eucommission/eu-commission-core.js',
                    args: [headless]
                };
                
                const result = await pluginAPI.runPluginScript(scriptParams);
                
                if (result.success) {
                    // EU Commission核心返回的是包含data字段的对象
                    let resultData = result.data || result;
                    
                    // 如果result本身就包含data字段，使用data字段
                    if (result.data && Array.isArray(result.data)) {
                        this.results = result.data;
                    } 
                    // 如果result直接是数组，直接使用
                    else if (Array.isArray(result)) {
                        this.results = result;
                    }
                    // 如果result是对象且包含data字段
                    else if (result && result.data) {
                        this.results = Array.isArray(result.data) ? result.data : [];
                    }
                    // 其他情况设为空数组
                    else {
                        this.results = [];
                    }
                    
                    // this.log(`抓取完成！共处理 ${this.results.length} 个页面`, 'success');
                    this.displayResults();
                } else {
                    throw new Error(result.error || '抓取失败');
                }
            } else {
                // 浏览器环境，使用模拟功能
                this.log('检测到浏览器环境，使用模拟模式', 'warning');
                await this.simulateScraping();
            }
        } catch (error) {
            throw new Error(`后端调用失败: ${error.message}`);
        }
    }

    // 处理进度更新
    handleProgressUpdate(progress) {
        if (progress.type === 'log') {
            this.log(progress.message, progress.level || 'info');
        } else if (progress.type === 'progress') {
            this.updateProgress(progress.current, progress.total, progress.message);
        }
    }

    // 模拟抓取过程（用于浏览器环境测试）
    async simulateScraping() {
        console.log('EU Commission UI: simulateScraping 开始执行');
        
        const targetCategories = [
            'Construction products (CPD/CPR)',
            'General product safety',
            'Personal protective equipment (PPE)',
            'Toy safety',
            'Low Voltage (LVD)',
            'Electromagnetic compatibility (EMC)',
            'Radio Equipment (RED)',
            'Medical devices (Regulation 2017/745)',
            'In vitro diagnostic medical devices (Regulation 2017/746)',
            'Gas appliances (GAR)',
            'Machinery (MD)',
            'Recreational craft and personal watercraft',
            'Pressure equipment (PED)',
            'Packaging and packaging waste',
            'Plastic caps and lids'
        ];

        this.log('正在访问EU Commission网站...', 'info');
        this.updateProgress(10, 100, '访问网站中...');
        await this.delay(1000);

        this.log('正在分析页面结构...', 'info');
        this.updateProgress(20, 100, '分析页面中...');
        await this.delay(1000);

        this.log('正在查找目标链接...', 'info');
        this.updateProgress(30, 100, '查找链接中...');
        await this.delay(1000);

        this.log(`找到 ${targetCategories.length} 个匹配的链接`, 'success');
        this.updateProgress(40, 100, '处理链接中...');

        // 模拟处理每个链接
        for (let i = 0; i < targetCategories.length; i++) {
            const category = targetCategories[i];
            this.log(`正在处理: ${category}`, 'info');
            
            await this.delay(300);
            this.log(`已在新标签页打开: ${category}`, 'info');
            
            await this.delay(300);
            const fileName = this.sanitizeFileName(category);
            this.log(`正在保存页面到: pages/${fileName}.html`, 'info');
            
            await this.delay(200);
            this.log(`页面保存完成: ${fileName}.html`, 'success');
            
            this.results.push({
                title: category,
                url: `https://single-market-economy.ec.europa.eu/single-market/goods/european-standards/harmonised-standards/${this.categoryToUrl(category)}_en`,
                fileName: `${fileName}.html`,
                timestamp: new Date().toISOString(),
                status: 'success'
            });
            
            const progress = 40 + ((i + 1) / targetCategories.length) * 60;
            this.updateProgress(progress, 100, `已处理 ${i + 1}/${targetCategories.length}`);
        }

        this.log(`抓取任务完成！共处理 ${this.results.length} 个页面`, 'success');
        this.displayResults();
    }

    // 将类别名称转换为URL格式
    categoryToUrl(category) {
        return category.toLowerCase()
            .replace(/\s+/g, '-')
            .replace(/[()]/g, '')
            .replace(/\//g, '-')
            .replace(/:/g, '')
            .replace(/,/g, '')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '');
    }

    // 清理文件名
    sanitizeFileName(fileName) {
        return fileName
            .replace(/[<>:"/\\|?*]/g, '_')
            .replace(/\s+/g, '_')
            .replace(/_+/g, '_')
            .replace(/^_|_$/g, '')
            .substring(0, 100);
    }

    // 清空结果显示
    clearResults() {
        if (this.resultsContainer) {
            this.resultsContainer.innerHTML = '';
        }
    }
    
    // 清空日志
    clearLogs() {
        if (this.logContainer) {
            this.logContainer.innerHTML = '等待操作...';
        }
    }

    // 显示结果
    displayResults() {
        console.log('EU Commission UI: 开始显示结果...');
        console.log('EU Commission UI: 结果数据:', this.results);
        console.log('EU Commission UI: 结果容器:', this.resultsContainer);
        
        if (!this.resultsContainer) {
            console.error('EU Commission UI: Results container not found');
            return;
        }

        if (!this.results || this.results.length === 0) {
            console.log('EU Commission UI: 没有结果数据，显示空状态');
            this.resultsContainer.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">未找到符合条件的数据</p>';
            return;
        }

        console.log(`EU Commission UI: 准备显示 ${this.results.length} 条结果`);
        
        // 过滤出有效的标准数据（非错误记录）
        const validResults = this.results.filter(r => !r.error && r.standard && r.standardName);
        const errorResults = this.results.filter(r => r.error);
        
        console.log('EU Commission UI: 统计信息:', { total: this.results.length, valid: validResults.length, error: errorResults.length });
        
        let html = `
            <div class="results-header">
                <h4>EU Commission 抓取结果 (${this.results.length} 条记录)</h4>
                <div class="results-stats">
                    <span class="stat-item">有效记录: ${validResults.length} 条</span>
                    <span class="stat-item">错误记录: ${errorResults.length} 条</span>
                </div>
            </div>
            <div class="results-table">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th style="width: 20%;">Standard</th>
                            <th style="width: 35%;">Standard Name</th>
                            <th style="width: 15%;">Region</th>
                            <th style="width: 15%;">Date of Publication</th>
                            <th style="width: 15%;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
        `;
        
        // 显示有效结果
        validResults.forEach(item => {
            const urlLink = item.url ? `<a href="${item.url}" target="_blank" class="btn btn-sm btn-outline-primary">查看详情</a>` : '-';
            
            html += `
                <tr>
                    <td><strong>${item.standard}</strong></td>
                    <td title="${item.standardName}">${item.standardName.length > 60 ? item.standardName.substring(0, 60) + '...' : item.standardName}</td>
                    <td><span class="region-badge">${item.region}</span></td>
                    <td>${item.dateOfPublication || '-'}</td>
                    <td>${urlLink}</td>
                </tr>
            `;
        });
        
        // 如果有错误记录，显示错误信息
        if (errorResults.length > 0) {
            html += `
                <tr class="table-warning">
                    <td colspan="5"><strong>错误记录 (${errorResults.length} 条)</strong></td>
                </tr>
            `;
            
            errorResults.forEach(item => {
                html += `
                    <tr class="table-danger">
                        <td>ERROR</td>
                        <td title="${item.standardName || '未知'}">${(item.standardName || '未知').length > 60 ? (item.standardName || '未知').substring(0, 60) + '...' : (item.standardName || '未知')}</td>
                        <td>${item.region || 'Europe'}</td>
                        <td>-</td>
                        <td><small class="text-danger">${item.errorMessage || '处理失败'}</small></td>
                    </tr>
                `;
            });
        }
        
        html += `
                    </tbody>
                </table>
            </div>
        `;
        
        this.resultsContainer.innerHTML = html;
        
        // 添加样式
        const style = document.createElement('style');
        style.textContent = `
            .results-header {
                margin-bottom: 20px;
                padding: 15px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 8px;
            }
            .results-header h4 {
                margin: 0 0 10px 0;
                font-weight: 600;
            }
            .results-stats {
                display: flex;
                gap: 20px;
            }
            .stat-item {
                background: rgba(255,255,255,0.2);
                padding: 5px 12px;
                border-radius: 15px;
                font-size: 14px;
            }
            .results-table {
                background: white;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .results-table table {
                margin: 0;
            }
            .results-table th {
                background: #f8f9fa;
                font-weight: 600;
                border-bottom: 2px solid #dee2e6;
            }
            .region-badge {
                background: #e3f2fd;
                color: #1976d2;
                padding: 3px 8px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 500;
            }
            .btn-outline-primary {
                font-size: 12px;
                padding: 2px 8px;
            }
        `;
        
        // 移除之前的样式并添加新样式
        const existingStyle = document.getElementById('eu-commission-ui-results-style');
        if (existingStyle) {
            existingStyle.remove();
        }
        style.id = 'eu-commission-ui-results-style';
        document.head.appendChild(style);
        
        console.log('EU Commission UI: 结果显示完成');
    }

    // 停止抓取
    async stopScraping() {
        if (!this.isRunning) {
            this.log('没有正在运行的抓取任务', 'warning');
            return;
        }

        this.log('正在停止抓取任务...', 'warning');
        
        try {
            if (typeof pluginAPI !== 'undefined') {
                // 调用pluginAPI.stopPluginScript方法停止脚本
                const taskId = pluginAPI.getCurrentTaskId();
                if (taskId) {
                    this.log(`正在停止任务 ${taskId}...`, 'info');
                    const result = await pluginAPI.stopPluginScript();
                    if (result.success) {
                        this.log('任务已成功停止', 'success');
                    } else {
                        this.log(`停止任务失败: ${result.error}`, 'error');
                    }
                } else {
                    this.log('没有找到正在运行的任务ID', 'warning');
                }
            }
        } catch (error) {
            this.log(`停止任务时发生错误: ${error.message}`, 'error');
        }
        
        this.isRunning = false;
        this.hideProgress();
        this.updateButtonStates();
        this.log('抓取任务已停止', 'info');
    }
    
    // 清理资源
    cleanup() {
        // 清理控制台监听器
        if (this.consoleLogListener && typeof consoleAPI !== 'undefined') {
            consoleAPI.removeConsoleLogListeners();
            this.consoleLogListener = null;
            console.log('EU Commission UI: 控制台监听器已清理');
        }
    }

    // 导出数据
    exportData() {
        if (this.results.length === 0) {
            this.log('没有可导出的数据', 'warning');
            return;
        }

        try {
            const dataStr = JSON.stringify(this.results, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });
            const url = URL.createObjectURL(dataBlob);
            
            const link = document.createElement('a');
            link.href = url;
            link.download = `eu-commission-results-${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            
            this.log(`数据已导出: ${this.results.length} 条记录`, 'success');
        } catch (error) {
            this.log(`导出失败: ${error.message}`, 'error');
        }
    }

    // 更新按钮状态
    updateButtonStates() {
        const startBtn = document.getElementById('eu-start-btn');
        const stopBtn = document.getElementById('eu-stop-btn');
        const exportBtn = document.getElementById('eu-export-btn');
        
        if (startBtn) {
            startBtn.disabled = this.isRunning;
            startBtn.textContent = this.isRunning ? '运行中...' : '开始抓取';
        }
        
        if (stopBtn) {
            stopBtn.disabled = !this.isRunning;
        }
        
        if (exportBtn) {
            exportBtn.disabled = this.results.length === 0;
        }
    }

    // 延迟函数
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 全局实例
let euCommissionUI = null;

// 初始化EU Commission UI功能
function initializeEUCommissionUI() {
    console.log('EU Commission UI: initializeEUCommissionUI 函数被调用');
    console.log('EU Commission UI: 当前 euCommissionUI 状态:', euCommissionUI);
    console.log('EU Commission UI: document.readyState:', document.readyState);
    
    if (euCommissionUI) {
        console.log('EU Commission UI 已经初始化过了');
        return; // 防止重复初始化
    }
    
    euCommissionUI = new EUCommissionUI();
    
    // 立即设置全局对象
    window.euCommissionUI = euCommissionUI;
    console.log('EU Commission UI: 全局对象已设置');
    
    // 等待DOM完全加载后再初始化元素
    if (document.readyState === 'loading') {
        console.log('EU Commission UI: DOM 正在加载，等待 DOMContentLoaded 事件');
        document.addEventListener('DOMContentLoaded', () => {
            console.log('EU Commission UI: DOMContentLoaded 事件触发，开始初始化元素');
            euCommissionUI.initializeElements();
        });
    } else {
        console.log('EU Commission UI: DOM 已就绪，立即初始化元素');
        euCommissionUI.initializeElements();
    }
    
    console.log('EU Commission UI 功能已注册');
}

// 页面加载时自动初始化
console.log('EU Commission UI: 脚本文件开始加载');
initializeEUCommissionUI();

console.log('EU Commission UI: 脚本文件加载完成');
console.log('EU Commission UI: window.euCommissionUI =', window.euCommissionUI);